<?php

namespace App\Kuafu\Base\Model\Traits;

use App\Kuafu\User\Model\User;
use App\Kuafu\User\Service\AuthService;

trait KfUid
{
    public static function bootKfUid()
    {
        static::saving(function ($model) {
            try {
                $operateUid = AuthService::getUserId();
            } catch (\Exception $e) {
                $operateUid = 0;
            }
            if ($operateUid == 0 && isset($model->createdByUid) && $model->createdByUid && $model->createdByUid > 0) {
                $operateUid = $model->createdByUid;
            }
            if (!$model->exists) {
                $model->setAttribute('createdByUid', $operateUid);
            }
            $model->setAttribute('updatedByUid', $operateUid);
        });
    }

    public function createdUser()
    {
//        return $this->belongsTo(User::class, 'createdByUid', 'id');
        return $this->hasOne(User::class, 'id', 'createdByUid');
    }

    public function updatedUser()
    {
//        return $this->belongsTo(User::class, 'updatedByUid', 'id');
        return $this->hasOne(User::class, 'id', 'updatedByUid');
    }
}
